<!-- 标注 -->
 
<template>
	<div class="container">
		<!-- 侧边栏 -->
		<div class="sidebar">
			<div class="sidebar-main">
				<div class="custom-card custom-input">
					<span>{{project['name']}}</span>
				</div>
				<div class="custom-card custom-info">
					<div 
						class="info-circle"
						:style="{ backgroundColor: currentMethodConfig?.color || '#409EFF' }"
					>
						{{ currentMethodConfig?.icon || '📊' }}
					</div>
					<div class="info-cont">
						<div class="title">
							{{ currentMethodConfig?.title || project?.instance?.title || '分类' }}
						</div>
						<div class="text">
							{{ currentMethodConfig?.description || project?.instance?.description || '' }}
						</div>
					</div>
				</div>
				<!-- 标注方式选择 -->
				<div class="custom-card annotation-settings">
					<div class="card-header">
						<div class="title">标注设置</div>
					</div>
					<div class="card-body">
						<div class="setting-section">
							<div class="annotation-modes">
								<div
									v-for="mode in annotationModes"
									:key="mode.key"
									class="mode-btn"
									:class="{ 
										active: annotationMode === mode.key,
										disabled: !imageTypes.length || (mode.key !== 'select' && !currentType)
									}"
									@click="handleModeChange(mode.key)"
									:title="!imageTypes.length 
										? '请先添加至少一个类别' 
										: (mode.key !== 'select' && !currentType) 
											? '请先选择一个类别' 
											: mode.description"
								>
									<el-icon><component :is="mode.icon"></component></el-icon>
									<span>{{ mode.title }}</span>
								</div>
							</div>
						</div>
						<div class="setting-section">
							<div class="setting-label">线条宽度</div>
							<div class="line-width-control">
								<el-slider
									v-model="lineWidth"
									:min="1"
									:max="10"
									:step="1"
									:show-tooltip="false"
									style="flex: 1"
								/>
								<span class="width-value">{{ lineWidth }}px</span>
								<div class="line-preview" :style="{ height: lineWidth + 'px' }"></div>
							</div>
						</div>
					</div>
				</div>
				<div class="custom-card custom-types">
					<div class="card-header">
						<div class="title">类别列表</div>
						<el-button @click="handleAddCategory" type="primary" size="small" circle>
							<el-icon><Plus /></el-icon>
						</el-button>
					</div>
					<div class="card-body">
						<div class="cell-box">
							<div 
							v-for="(item,index) in imageTypes"
							:key="index"
							class="cell citem"
							:class="{ active: item.key == currentType }"
							@click="handleCategoryClick(item)"
							@dblclick="handleCategoryDoubleClick(item)"
							>
								<div 
									class="color-picker-wrapper"
									:style="{ backgroundColor: item.color }"
									@click.stop="showColorPicker(item)"
								></div>
								<div class="category-content">
									<input 
										v-if="editingCategory === item.key"
										v-model="editingCategoryTitle"
										@blur="handleSaveCategory(item.key)"
										@keyup.enter="handleSaveCategory(item.key)"
										@keyup.esc="cancelEditCategory"
										class="category-input"
										ref="categoryInput"
									/>
									<span v-else>{{ item.title }}</span>
								</div>
								<div class="category-actions" @click.stop>
									<el-icon 
										v-if="editingCategory !== item.key"
										@click="handleEditCategoryStart(item)" 
										class="action-icon edit-icon"
										title="编辑类别"
									><Edit /></el-icon>
									<el-icon 
										@click="handleDeleteCategory(item.key)" 
										class="action-icon delete-icon"
										title="删除类别"
									><Delete /></el-icon>
								</div>
							</div>
						</div>
						<div class="card-buttons">
							<div class="btn">开始训练</div>
						</div>
					</div>
				</div>
				<div class="custom-card custom-types">
					<div class="card-header">
						<div class="title">标注列表</div>
					</div>
					<div class="card-body">
						<div class="cell-box" style="border: 0">
							<div
							v-for="(item,index) in imageTags.slice().reverse()"
							:key="index"
							class="cell tag-item"
							:class="{active: item.key == currentTag}"
							@click="handleChangeTag(item)"
							>
								<div 
								:style="{background: item.color}"
								class="color"></div>
								<div class="tag-info">
									<div class="tag-row">
										<div class="tag-title">{{item.displayText}}</div>
										<div class="tag-coords">{{item.coords}}</div>
									</div>
									<div class="tag-area">面积: {{item.area}}px²</div>
								</div>
								<div class="tag-actions" @click.stop>
									<el-icon 
										@click="handleDeleteTag(item.key)" 
										class="action-icon delete-icon"
										title="删除标注"
									><Delete /></el-icon>
								</div>
							</div>
						</div>
						<div class="card-buttons">
							<div class="btn btn-left" @click="moveAnnotationLayer('up')">上移</div>
							<div class="btn" @click="moveAnnotationLayer('down')">下移</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 主内容区域 -->
		<div class="content">
			<div class="tags-box">
				<div
				v-for="(item,index) in tags"
				:key="index"
				:class="[
					'tag',
					{ 'divider': item.mode === 'divider' },
					{ 'disabled': 
						(item.key === 'export' && !imageTags.length) ||
						(item.key === 'undo' && newAnnotationIds.length === 0) ||
						(item.key === 'redo' && !imageTags.length)
					}
				]"
				@click="handelTap(item)"
				>	
					<el-icon v-if="item.icon" :size="13"><component :is="item.icon"></component></el-icon>
					<span v-if="item.title">
						{{ item.title }}
					</span>
				</div>
			</div>
			<div class="content-main" v-if="currentImage">
				<div 
					class="image-container" 
					ref="imageContainerRef"
					:style="{ transform: `scale(${currentScale})` }"
				>
					<img 
						ref="imageRef"
						:src="getImageUrl(currentImage)" 
						class="img" 
						:alt="currentImage.name"
						@error="handleImageError"
						@load="handleImageLoad"
					/>
					<!-- 标注覆盖层 -->
					<div class="annotation-overlay">
						<!-- 标注元素由annotationDrawer.js动态创建和管理 -->
					</div>
				</div>
			</div>
			<div class="content-main no-image" v-else>
				<div class="no-image-placeholder">
					<el-icon :size="48"><Picture /></el-icon>
					<p>请从图库页面选择一张图片进行标注</p>
				</div>
			</div>
			<div class="custom-footer">
				<div>{{ currentImage ? `${currentImage.name} (${currentImage.size || '未知尺寸'})` : '' }}</div>
				<div>XY({{ mousePosition.x }}, {{ mousePosition.y }})</div>
				<div class="rgb-info">
					<span>RGB({{ mousePosition.rgb }})</span>
					<div 
						class="color-preview" 
						:style="{ backgroundColor: mousePosition.hex }"
						:title="mousePosition.hex"
					></div>
				</div>
			</div>
		</div>
		
		<!-- 颜色选择器对话框 -->
		<el-dialog
			v-model="colorPickerVisible"
			title="选择颜色"
			width="400px"
			:modal="true"
			:close-on-click-modal="false"
		>
			<div class="color-picker-dialog">
				<div class="color-picker-section">
					<label for="colorInput">选择颜色:</label>
					<input 
						id="colorInput"
						type="color" 
						v-model="selectedColor"
						class="native-color-picker"
					/>
					<span class="color-value">{{ selectedColor }}</span>
				</div>
				
				<div class="preset-colors-section">
					<div class="preset-title">预设颜色:</div>
					<div class="preset-colors-grid">
						<div
							v-for="preset in colorPresets"
							:key="preset"
							class="preset-color-item"
							:style="{ backgroundColor: preset }"
							@click="selectedColor = preset"
							:title="preset"
						></div>
					</div>
				</div>
			</div>
			
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelColorChange">取消</el-button>
					<el-button type="primary" @click="confirmColorChange">确认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { ElMessage, ElMessageBox } from 'element-plus'
	import {
		ref,
		onMounted,
		computed,
		watch,
		nextTick
	} from 'vue'
	import { useProjectStore } from '@store';
	import { useMouseTracker } from '../utils/mouseTracker';
	import { useRoute, useRouter } from 'vue-router';
	import { useAnnotationDrawer } from '../utils/annotationDrawer';
	import { cropAnnotationImage } from '../utils/imageCropper';
	
	const projectStore = useProjectStore();
	const route = useRoute();
	const router = useRouter();
	const project = computed(() => projectStore.getProject)
	const currentImage = computed(() => projectStore.getImageInfo)
	
	// 加载本地方法配置
	const instanceList = ref([])
	const currentMethodConfig = computed(() => {
		if (!project.value?.instance?.id || !instanceList.value.length) {
			return null
		}
		return instanceList.value.find(method => method.id === project.value.instance.id)
	})

	// 标注类别管理 - 每张图片独立的类别定义
	const imageTypes = ref([])
	const currentType = ref(null)
	
	// 从当前图片加载类别列表
	const loadCategoriesFromCurrentImage = () => {
		if (currentImage.value?.categories && Array.isArray(currentImage.value.categories)) {
			imageTypes.value = [...currentImage.value.categories]
		} else {
			// 如果当前图片没有类别定义，初始化为空
			imageTypes.value = []
		}
		
		// 重置当前选中的类别
		currentType.value = null
		// 如果有类别，选中第一个
		if (imageTypes.value.length > 0) {
			currentType.value = imageTypes.value[0].key
		}
	}
	
	// 保存类别列表到当前图片
	const saveCategoriesToCurrentImage = async () => {
		if (!currentImage.value) return
		
		try {
			// 更新当前图片的类别数据
			currentImage.value.categories = [...imageTypes.value]
			
			// 保存到项目
			await saveImageDataToProject()
			
			console.log('[Images] 当前图片的类别数据已保存')
		} catch (error) {
			console.error('[Images] 保存类别数据失败:', error)
			ElMessage.error('保存类别数据失败: ' + error.message)
		}
	}

	// 计算多边形面积
	const calculatePolygonArea = (points) => {
		if (!points || points.length < 3) return 0
		
		let area = 0
		for (let i = 0; i < points.length; i++) {
			const j = (i + 1) % points.length
			area += points[i].x * points[j].y
			area -= points[j].x * points[i].y
		}
		return Math.abs(area / 2)
	}
	
	// 带详细信息（颜色、显示文本）的标注列表，用于渲染
	const annotationsWithDetails = computed(() => {
		if (!currentImage.value || !currentImage.value.annotations) {
			return []
		}
		
		// 首先确保所有标注都有zIndex
		const annotations = currentImage.value.annotations.map((annotation, index) => ({
			...annotation,
			zIndex: typeof annotation.zIndex === 'number' ? annotation.zIndex : index
		}))
		
		// 按zIndex排序，确保渲染顺序正确（zIndex小的先渲染，在底层）
		const sortedAnnotations = [...annotations].sort((a, b) => a.zIndex - b.zIndex)
		
		console.log('[Images] annotationsWithDetails 排序后的标注:', sortedAnnotations.map(ann => ({
			id: ann.id,
			zIndex: ann.zIndex,
			categoryId: ann.categoryId
		})))
		
		const categoryCounters = {}
		return sortedAnnotations.map((annotation) => {
			const categoryId = annotation.categoryId
			const category = imageTypes.value.find(type => type.key === categoryId)
			const categoryTitle = category?.title || '未知类别'
			const categoryColor = category?.color || '#999999'
			
			if (!categoryCounters[categoryId]) {
				categoryCounters[categoryId] = 0
			}
			categoryCounters[categoryId]++
			const categoryIndex = categoryCounters[categoryId]
			
			return {
				...annotation,
				color: categoryColor,
				title: categoryTitle,
				displayText: `${categoryTitle} #${categoryIndex}`
			}
		})
	})
	
	// 当前图像的标注数据
	const imageTags = computed(() => {
		if (!currentImage.value || !currentImage.value.annotations) {
			return []
		}
		
		// 首先确保所有标注都有zIndex
		const annotations = currentImage.value.annotations.map((annotation, index) => ({
			...annotation,
			zIndex: typeof annotation.zIndex === 'number' ? annotation.zIndex : index
		}))
		
		// 按zIndex排序，确保与annotationsWithDetails的排序方向一致
		// 然后在模板中使用 .slice().reverse() 来显示时让顶层在上方
		const sortedAnnotations = [...annotations].sort((a, b) => a.zIndex - b.zIndex)
		
		// 按类别分组计数
		const categoryCounters = {}
		
		console.log('[Images] imageTags 排序后的标注:', sortedAnnotations.map(ann => ({
			id: ann.id,
			zIndex: ann.zIndex,
			categoryId: ann.categoryId
		})))
		
		return sortedAnnotations.map((annotation) => {
			const categoryId = annotation.categoryId
			const category = imageTypes.value.find(type => type.key === categoryId)
			const categoryTitle = category?.title || '未知类别'
			const categoryColor = category?.color || '#999999'
			
			// 计算该类别下的序号
			if (!categoryCounters[categoryId]) {
				categoryCounters[categoryId] = 0
			}
			categoryCounters[categoryId]++
			const categoryIndex = categoryCounters[categoryId]
			
			// 计算面积和坐标
			let area = 0
			let startX = 0
			let startY = 0
			let coords = ''
			
			if (annotation.type === 'rectangle') {
				area = Math.round((annotation.width || 0) * (annotation.height || 0))
				startX = annotation.x || 0
				startY = annotation.y || 0
				coords = `(${Math.round(startX)}, ${Math.round(startY)})`
			} else if (annotation.type === 'line-polygon') {
				if (annotation.points && annotation.points.length > 0) {
					area = Math.round(calculatePolygonArea(annotation.points))
					startX = annotation.points[0].x
					startY = annotation.points[0].y
					coords = `(${Math.round(startX)}, ${Math.round(startY)})`
				}
			} else if (annotation.type === 'point') {
				area = 1 // 点标注面积为1
				startX = annotation.x || 0
				startY = annotation.y || 0
				coords = `(${Math.round(startX)}, ${Math.round(startY)})`
			}
			
			return {
				key: annotation.id,
				title: categoryTitle,
				color: categoryColor,
				categoryIndex: categoryIndex,
				x: startX,
				y: startY,
				width: annotation.width,
				height: annotation.height,
				coords: coords,
				area: area,
				rgb: annotation.rgb || '255,255,255',
				type: annotation.type || 'rectangle',
				displayText: `${categoryTitle} #${categoryIndex}`
			}
		})
	})
	const currentTag = ref('')
	// 标注工具栏配置
	const annotationMode = ref('') // 当前标注模式，初始为空
	const lineWidth = ref(2) // 线条宽度
	const currentScale = ref(1.0) // 当前缩放比例
	const minScale = 0.1 // 最小缩放比例
	
	// 标注模式配置
	const annotationModes = ref([
		{ 
			key: 'select', 
			title: '选择', 
			icon: 'Pointer', 
			description: '选择和移动标注'
		},
		{ 
			key: 'rectangle', 
			title: '矩形', 
			icon: 'Grid', 
			description: '绘制矩形标注框'
		},
		{ 
			key: 'point', 
			title: '点标注', 
			icon: 'Location', 
			description: '添加点标注'
		}
	])
	
	
	// 类别编辑状态
	const editingCategory = ref(null)
	const editingCategoryTitle = ref('')
	
	// 颜色选择器状态
	const colorPickerVisible = ref(false)
	const colorPickerCategory = ref(null)
	const selectedColor = ref('#409EFF')
	
	// 标注状态管理
	// 新创建的标注ID列表（载入后新增的）
	const newAnnotationIds = ref([])
	
	// 颜色预设
	const colorPresets = ref([
		'#F93A4A',  // 红色
		'#FF9F18',  // 橙色
		'#FFD93D',  // 黄色
		'#00B578',  // 绿色
		'#1677FF',  // 蓝色
		'#9C27B0',  // 紫色
		'#FF5722',  // 深橙色
		'#795548',  // 棕色
		'#607D8B',  // 蓝灰色
		'#E91E63',  // 粉红色
		'#00BCD4',  // 青色
		'#4CAF50'   // 亮绿色
	])
	
	// 工具栏按钮
	const tags = ref([
		{ key: 'import', title: '导入', icon: 'FolderOpened', mode: 'action' },
		{ key: 'export', title: '导出', icon: 'Upload', mode: 'action' },
		{ key: 'divider1', title: '', icon: '', mode: 'divider' },
		{ key: 'undo', title: '撤销', icon: 'RefreshLeft', mode: 'action' },
		{ key: 'redo', title: '清空', icon: 'Delete', mode: 'action' },
		{ key: 'divider2', title: '', icon: '', mode: 'divider' },
		{ key: 'prev', title: '上一张', icon: 'ArrowLeft', mode: 'action' },
		{ key: 'next', title: '下一张', icon: 'ArrowRight', mode: 'action' },
		{ key: 'divider3', title: '', icon: '', mode: 'divider' },
		{ key: 'zoomIn', title: '放大', icon: 'ZoomIn', mode: 'action' },
		{ key: 'zoomOut', title: '缩小', icon: 'ZoomOut', mode: 'action' },
		{ key: 'fit', title: '适应窗口', icon: 'Reading', mode: 'action' },
		{ key: 'help', title: '帮助', icon: 'QuestionFilled', mode: 'action' },
	])
	// 处理类别单击 - 切换选中状态
	const handleCategoryClick = (item) => {
		// 如果点击的是当前选中的类别，则取消选中
		if (currentType.value === item.key) {
			currentType.value = null
		} else {
			// 否则选中该类别
			currentType.value = item.key
		}
		
		currentTag.value = null // 清空单个标注的选中
		updateAnnotationHighlight()
		console.log('[Images] 切换标注类别:', item.title, '选中状态:', currentType.value === item.key)
	}
	
	// 处理类别双击 - 高亮该类别下的所有标注
	const handleCategoryDoubleClick = (item) => {
		
		// 选中该类别
		currentType.value = item.key
		currentTag.value = null // 清空单个标注的选中
		
		// 高亮该类别下的所有标注
		highlightCategoryAnnotations(item.key)
		
		ElMessage.success(`已高亮类别 "${item.title}" 的所有标注`)
		console.log('[Images] 双击类别，高亮所有标注:', item.title)
	}
	
	// 高亮指定类别的所有标注
	const highlightCategoryAnnotations = (categoryKey) => {
		if (!imageContainerRef.value) return
		
		// 移除所有现有高亮
		const highlightedElements = imageContainerRef.value.querySelectorAll('.annotation-shape.highlighted')
		highlightedElements.forEach(el => el.classList.remove('highlighted'))
		
		// 为该类别下的所有标注添加高亮
		if (currentImage.value?.annotations) {
			currentImage.value.annotations.forEach(annotation => {
				if (annotation.categoryId === categoryKey) {
					const targetContainer = imageContainerRef.value.querySelector(`#annotation-${annotation.id}`)
					if (targetContainer) {
						// 尝试在容器内部寻找 shape 元素
						let shapeElement = targetContainer.querySelector('.annotation-shape')
						// 如果内部没有，则检查容器本身是否就是 shape 元素
						if (!shapeElement && targetContainer.classList.contains('annotation-shape')) {
							shapeElement = targetContainer
						}
						
						if (shapeElement) {
							shapeElement.classList.add('highlighted')
						}
					}
				}
			})
		}
	}
	

	// 处理标注模式切换
	const handleModeChange = (mode) => {
		// 所有模式都检查是否有类别
		if (!imageTypes.value || imageTypes.value.length === 0) {
			ElMessage.warning('请先添加至少一个类别才能使用标注功能')
			return
		}
		
		// 如果切换到标注模式（非选择模式），还要检查是否选中了类别
		if (mode !== 'select') {
			if (!currentType.value) {
				ElMessage.warning('请先选择一个类别才能进行标注')
				return
			}
		}
		
		annotationMode.value = mode
		annotationDrawer.setAnnotationMode(mode)
		console.log('[Images] 切换标注模式:', mode)
		const modeConfig = annotationModes.value.find(m => m.key === mode)
		if (modeConfig) {
			ElMessage.success(`切换到${modeConfig.title}模式`)
		}
	}

	// 处理标注单击 - 切换选中状态
	const handleChangeTag = (item) => {
		console.log('[Images] 点击标注:', {
			displayText: item.displayText,
			key: item.key,
			currentTag: currentTag.value,
			item: item
		})
		
		// 如果点击的是当前选中的标注，则取消选中
		if (currentTag.value === item.key) {
			currentTag.value = null
			console.log('[Images] 取消选中标注')
		} else {
			// 否则选中该标注
			currentTag.value = item.key
			console.log('[Images] 选中标注:', item.key)
		}
		
		currentType.value = null // 清空类别的选中
		updateAnnotationHighlight()
		console.log('[Images] 切换标注选中状态:', item.displayText, '最终currentTag:', currentTag.value)
	}

	// 处理工具栏点击
	const handelTap = (item) => {
		if (item.mode === 'divider') return
		
		// 检查按钮是否被禁用
		if (item.key === 'export' || item.key === 'redo') {
			if (!imageTags.value.length) {
				ElMessage.warning('当前图像没有标注数据')
				return
			}
		} else if (item.key === 'undo') {
			if (newAnnotationIds.value.length === 0) {
				ElMessage.warning('没有可撤销的新标注')
				return
			}
		}
		
		switch (item.key) {
			case 'import':
				handleImportAnnotations()
				break
			case 'export':
				handleExportAnnotations()
				break
			case 'undo':
				handleUndo()
				break
			case 'redo':
				handleRedo()
				break
			case 'prev':
				handlePrevImage()
				break
			case 'next':
				handleNextImage()
				break
			case 'zoomIn':
				handleZoomIn()
				break
			case 'zoomOut':
				handleZoomOut()
				break
			case 'fit':
				handleFitWindow()
				break
			case 'help':
				handleShowHelp()
				break
			default:
				ElMessage(item.title)
		}
	}

	// 标注相关操作函数

	const handleImportAnnotations = async () => {
		try {
			console.log('[Images] 开始导入JSON文件...')
			
			// 打开文件选择对话框
			const filters = [
				{ name: 'JSON Files', extensions: ['json'] },
				{ name: 'All Files', extensions: ['*'] }
			]
			
			const filePaths = await window.electronAPI.openFileDialog(filters)
			if (!filePaths || filePaths.length === 0) {
				console.log('[Images] 用户取消了文件选择')
				return
			}
			
			const filePath = filePaths[0]
			console.log('[Images] 选择的文件:', filePath)
			
			// 读取JSON文件内容
			const fileResult = await window.electronAPI.readFile(filePath)
			if (!fileResult.success) {
				ElMessage.error('读取文件失败: ' + fileResult.error)
				return
			}
			const fileContent = fileResult.content
			
			// 解析JSON
			let importData
			try {
				importData = JSON.parse(fileContent)
			} catch (parseError) {
				console.error('[Images] JSON解析失败:', parseError)
				ElMessage.error('JSON文件格式错误，请检查文件格式')
				return
			}
			
			// 验证JSON格式
			const validationResult = validateImportData(importData)
			if (!validationResult.valid) {
				console.error('[Images] JSON格式验证失败:', validationResult.errors)
				ElMessage.error(`JSON格式验证失败: ${validationResult.errors.join(', ')}`)
				return
			}
			
			// 确认导入操作
			const confirmResult = await ElMessageBox.confirm(
				`确定要导入标注数据吗？这将覆盖当前的所有标注数据。\n\n导入的数据包含:\n- 图片: ${importData.image?.name || '未知'}\n- 标注数量: ${importData.annotations?.length || 0}\n- 类别数量: ${importData.categories?.length || 0}`,
				'确认导入',
				{
					confirmButtonText: '确定导入',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
			
			if (confirmResult !== 'confirm') {
				return
			}
			
			// 执行导入
			await performImport(importData)
			
			ElMessage.success('JSON文件导入成功!')
			
		} catch (error) {
			console.error('[Images] 导入JSON文件失败:', error)
			ElMessage.error('导入失败: ' + error.message)
		}
	}

	// 验证导入数据格式
	const validateImportData = (data) => {
		const errors = []
		
		// 检查基本结构
		if (!data || typeof data !== 'object') {
			errors.push('JSON文件必须是一个对象')
			return { valid: false, errors }
		}
		
		// 检查image字段
		if (!data.image || typeof data.image !== 'object') {
			errors.push('缺少image字段或格式错误')
		} else {
			if (!data.image.id) errors.push('image.id字段缺失')
			if (!data.image.name) errors.push('image.name字段缺失')
			if (!data.image.path) errors.push('image.path字段缺失')
		}
		
		// 检查categories字段
		if (!Array.isArray(data.categories)) {
			errors.push('categories字段必须是数组')
		} else {
			data.categories.forEach((category, index) => {
				if (!category.key) errors.push(`categories[${index}].key字段缺失`)
				if (!category.title) errors.push(`categories[${index}].title字段缺失`)
				if (!category.color) errors.push(`categories[${index}].color字段缺失`)
			})
		}
		
		// 检查annotations字段
		if (!Array.isArray(data.annotations)) {
			errors.push('annotations字段必须是数组')
		} else {
			data.annotations.forEach((annotation, index) => {
				if (!annotation.id) errors.push(`annotations[${index}].id字段缺失`)
				if (!annotation.type) errors.push(`annotations[${index}].type字段缺失`)
				if (!annotation.categoryId) errors.push(`annotations[${index}].categoryId字段缺失`)
				
				// 根据类型验证坐标数据
				if (annotation.type === 'rectangle') {
					if (typeof annotation.x !== 'number') errors.push(`annotations[${index}].x字段缺失或格式错误`)
					if (typeof annotation.y !== 'number') errors.push(`annotations[${index}].y字段缺失或格式错误`)
					if (typeof annotation.width !== 'number') errors.push(`annotations[${index}].width字段缺失或格式错误`)
					if (typeof annotation.height !== 'number') errors.push(`annotations[${index}].height字段缺失或格式错误`)
				} else if (annotation.type === 'line-polygon') {
					if (!Array.isArray(annotation.points)) {
						errors.push(`annotations[${index}].points字段缺失或格式错误`)
					} else {
						annotation.points.forEach((point, pointIndex) => {
							if (typeof point.x !== 'number') errors.push(`annotations[${index}].points[${pointIndex}].x字段格式错误`)
							if (typeof point.y !== 'number') errors.push(`annotations[${index}].points[${pointIndex}].y字段格式错误`)
						})
					}
				} else if (annotation.type === 'point') {
					if (typeof annotation.x !== 'number') errors.push(`annotations[${index}].x字段缺失或格式错误`)
					if (typeof annotation.y !== 'number') errors.push(`annotations[${index}].y字段缺失或格式错误`)
				}
			})
		}
		
		return {
			valid: errors.length === 0,
			errors
		}
	}
	
	// 执行导入操作
	const performImport = async (importData) => {
		try {
			console.log('[Images] 开始执行导入操作...')
			
			// 更新当前图片的数据
			if (currentImage.value) {
				// 更新类别数据
				currentImage.value.categories = [...importData.categories]
				imageTypes.value = [...importData.categories]
				
				// 更新标注数据
				currentImage.value.annotations = [...importData.annotations]
				
				// 保存到项目
				await saveImageDataToProject()
				
				// 重新加载类别和标注
				loadCategoriesFromCurrentImage()
				
				// 如果标注绘制器已初始化，重新渲染标注
				if (annotationDrawer) {
					annotationDrawer.clearAllAnnotations()
					annotationDrawer.renderExistingAnnotations(annotationsWithDetails.value)
				}
				
				// 更新状态
				newAnnotationIds.value = []
				
				console.log('[Images] 导入操作完成')
			}
		} catch (error) {
			console.error('[Images] 执行导入操作失败:', error)
			throw error
		}
	}

	const handleExportAnnotations = async () => {
		if (!currentImage.value) {
			ElMessage.warning('请先选择一张图片')
			return
		}
		
		if (!imageTags.value.length) {
			ElMessage.warning('当前图像没有标注数据')
			return
		}
		
		try {
			console.log('[Images] 开始导出标注数据...')
			
			// 准备导出的数据
			const exportData = {
				image: {
					id: currentImage.value.id,
					name: currentImage.value.name,
					path: currentImage.value.path,
					size: currentImage.value.size,
					width: currentImage.value.width || 0,
					height: currentImage.value.height || 0,
					createTime: currentImage.value.createTime || new Date().toISOString()
				},
				categories: imageTypes.value || [],
				annotations: currentImage.value.annotations || [],
				statistics: {
					totalAnnotations: imageTags.value.length,
					categoriesCount: imageTypes.value.length,
					exportTime: new Date().toISOString(),
					version: '1.0.0'
				}
			}
			
			// 使用Electron API选择保存位置
			if (window.electronAPI?.showSaveDialog) {
				const result = await window.electronAPI.showSaveDialog({
					title: '导出标注数据',
					defaultPath: `${currentImage.value.name}_annotations.json`,
					filters: [
						{ name: 'JSON文件', extensions: ['json'] },
						{ name: '所有文件', extensions: ['*'] }
					]
				})
				
				if (!result.canceled && result.filePath) {
					// 保存文件
					const saveResult = await window.electronAPI.saveJsonFile(result.filePath, exportData)
					if (saveResult.success) {
						ElMessage.success(`标注数据已导出到: ${result.filePath}`)
						console.log('[Images] 导出成功:', result.filePath)
					} else {
						throw new Error(saveResult.error || '保存文件失败')
					}
				}
			} else {
				// 降级方案：下载到浏览器默认下载目录
				const jsonString = JSON.stringify(exportData, null, 2)
				const blob = new Blob([jsonString], { type: 'application/json' })
				const url = URL.createObjectURL(blob)
				
				const a = document.createElement('a')
				a.href = url
				a.download = `${currentImage.value.name}_annotations.json`
				document.body.appendChild(a)
				a.click()
				document.body.removeChild(a)
				URL.revokeObjectURL(url)
				
				ElMessage.success('标注数据已下载')
			}
		} catch (error) {
			console.error('[Images] 导出标注数据失败:', error)
			ElMessage.error('导出失败: ' + error.message)
		}
	}

	const handleUndo = async () => {
		if (!currentImage.value) {
			ElMessage.warning('请先选择一张图片')
			return
		}
		
		if (newAnnotationIds.value.length === 0) {
			ElMessage.warning('没有可撤销的新标注')
			return
		}
		
		try {
			// 获取最后一个新创建的标注ID
			const lastNewAnnotationId = newAnnotationIds.value.pop()
			
			// 从标注数组中删除该标注
			const annotationIndex = currentImage.value.annotations.findIndex(ann => ann.id === lastNewAnnotationId)
			if (annotationIndex > -1) {
				const removedAnnotation = currentImage.value.annotations.splice(annotationIndex, 1)[0]
				console.log('[Images] 撤销新标注:', removedAnnotation.id)
				
				// 从DOM中移除对应的标注元素
				if (annotationDrawer) {
					annotationDrawer.removeAnnotation(removedAnnotation.id)
				}
				
				// 保存更改到项目
				await saveImageDataToProject()
				
				// 刷新显示
				refreshAnnotationDisplay()
				
				ElMessage.success(`已撤销新标注 (还可撤销 ${newAnnotationIds.value.length} 个新标注)`)
			} else {
				ElMessage.warning('未找到要撤销的标注')
			}
		} catch (error) {
			console.error('[Images] 撤销操作失败:', error)
			ElMessage.error('撤销失败: ' + error.message)
		}
	}

	const handleRedo = async () => {
		if (!currentImage.value) {
			ElMessage.warning('请先选择一张图片')
			return
		}
		
		if (!currentImage.value.annotations || currentImage.value.annotations.length === 0) {
			ElMessage.warning('没有可删除的标注')
			return
		}
		
		// 确认对话框
		try {
			await ElMessageBox.confirm(
				`确定要删除当前图片的所有 ${currentImage.value.annotations.length} 个标注吗？此操作不可恢复。`,
				'删除所有标注',
				{
					confirmButtonText: '确定删除',
					cancelButtonText: '取消',
					type: 'warning',
					confirmButtonClass: 'el-button--danger'
				}
			)
			
			console.log('[Images] 开始删除所有标注...')
			
			// 清空标注数组
			const deletedCount = currentImage.value.annotations.length
			currentImage.value.annotations = []
			
			// 清空DOM中的标注显示
			if (annotationDrawer) {
				annotationDrawer.clearAllAnnotations()
			}
			
			// 保存更改到项目
			await saveImageDataToProject()
			
			// 刷新显示
			refreshAnnotationDisplay()
			
			ElMessage.success(`已删除所有标注 (共 ${deletedCount} 个)`)
		} catch (error) {
			if (error === 'cancel') {
				console.log('[Images] 用户取消删除操作')
			} else {
				console.error('[Images] 删除所有标注失败:', error)
				ElMessage.error('删除失败: ' + error.message)
			}
		}
	}

	const handlePrevImage = () => {
		if (!project.value?.images || project.value.images.length <= 1) {
			ElMessage.warning('没有更多图像')
			return
		}
		
		const currentImageId = projectStore.getCurrentImgId
		const currentIndex = project.value.images.findIndex(img => img.id === currentImageId)
		
		if (currentIndex > 0) {
			const prevImage = project.value.images[currentIndex - 1]
			projectStore.setImageInfo(prevImage)
			projectStore.setCurrentImg(prevImage.id)
			ElMessage.success(`切换到: ${prevImage.name}`)
		} else {
			ElMessage.warning('已经是第一张图像')
		}
	}

	const handleNextImage = () => {
		if (!project.value?.images || project.value.images.length <= 1) {
			ElMessage.warning('没有更多图像')
			return
		}
		
		const currentImageId = projectStore.getCurrentImgId
		const currentIndex = project.value.images.findIndex(img => img.id === currentImageId)
		
		if (currentIndex < project.value.images.length - 1) {
			const nextImage = project.value.images[currentIndex + 1]
			projectStore.setImageInfo(nextImage)
			projectStore.setCurrentImg(nextImage.id)
			ElMessage.success(`切换到: ${nextImage.name}`)
		} else {
			ElMessage.warning('已经是最后一张图像')
		}
	}

	const handleZoomIn = () => {
		if (!imageRef.value || !imageContainerRef.value) return

		const newScale = currentScale.value * 1.1
		
		// 获取父容器（内容区）的尺寸作为边界
		const container = imageContainerRef.value.parentElement
		if (!container) return
		
		const containerWidth = container.clientWidth
		const containerHeight = container.clientHeight
		
		// 获取图片在当前DOM中的渲染尺寸（未缩放前）
		const imageRenderWidth = imageRef.value.offsetWidth
		const imageRenderHeight = imageRef.value.offsetHeight
		
		// 检查放大后是否会超出任一边界
		if (imageRenderWidth * newScale > containerWidth || imageRenderHeight * newScale > containerHeight) {
			ElMessage.warning('已达到最大缩放')
			// 可以选择计算一个恰好填满的精确缩放比例
			const scaleX = containerWidth / imageRenderWidth
			const scaleY = containerHeight / imageRenderHeight
			currentScale.value = Math.min(scaleX, scaleY)
			return
		}
		
		currentScale.value = newScale
	}

	const handleZoomOut = () => {
		if (!imageRef.value) return
		
		const newScale = currentScale.value / 1.1
		
		if (newScale < minScale) {
			ElMessage.warning('已达到最小缩放')
			currentScale.value = minScale
			return
		}
		
		currentScale.value = newScale
	}

	const handleFitWindow = () => {
		currentScale.value = 1.0
		ElMessage('已适应窗口')
	}

	const handleShowHelp = () => {
		ElMessage('显示帮助信息')
	}

	// 添加新类别
	const handleAddCategory = async () => {

		if (!currentImage.value) {
			ElMessage.warning('请先选择一张图片')
			return
		}
		
		const newCategory = {
			key: Math.max(...imageTypes.value.map(t => t.key), 0) + 1,
			title: '类别',
			color: colorPresets.value[imageTypes.value.length % colorPresets.value.length]
		}
		imageTypes.value.push(newCategory)
		
		// 如果这是第一个类别，自动选中它
		if (imageTypes.value.length === 1) {
			currentType.value = newCategory.key
		}
		
		// 保存到当前图片
		await saveCategoriesToCurrentImage()
		
		ElMessage.success('添加新类别成功')
	}
	
	// 显示颜色选择器
	const showColorPicker = (category) => {
		console.log('[Images] 显示颜色选择器:', category)
		colorPickerCategory.value = category
		selectedColor.value = category.color || '#409EFF'
		colorPickerVisible.value = true
	}
	
	// 确认颜色选择
	const confirmColorChange = async () => {
		if (colorPickerCategory.value) {
			console.log('[Images] 确认颜色变化:', colorPickerCategory.value.title, selectedColor.value)
			await handleColorChange(colorPickerCategory.value.key, selectedColor.value)
			
			// 等待一个tick确保所有更新完成
			await nextTick()
			
			// 再次强制刷新以确保显示更新
			setTimeout(() => {
				refreshAnnotationDisplay()
			}, 100)
		}
		colorPickerVisible.value = false
		colorPickerCategory.value = null
	}
	
	// 取消颜色选择
	const cancelColorChange = () => {
		colorPickerVisible.value = false
		colorPickerCategory.value = null
	}

	// 处理颜色变化
	const handleColorChange = async (categoryKey, newColor) => {
		const category = imageTypes.value.find(type => type.key === categoryKey)
		if (category && newColor) {
			category.color = newColor
			console.log(`[Images] 类别 ${category.title} 颜色已更改为: ${newColor}`)
			
			// 更新当前图片上该类别的所有标注颜色
			await updateAnnotationColors(categoryKey)
			
			// 保存到当前图片
			await saveCategoriesToCurrentImage()
			
			// 重新渲染标注以应用新颜色
			refreshAnnotationDisplay()
			
			// 如果当前修改的是选中的类别，同步更新标注绘制器的当前类别
			if (currentType.value === categoryKey) {
				const updatedCategory = imageTypes.value.find(type => type.key === categoryKey)
				if (updatedCategory && annotationDrawer) {
					annotationDrawer.setCurrentCategory(updatedCategory)
				}
			}
			
			// 显示成功消息
			ElMessage.success(`类别 "${category.title}" 的颜色已更新，所有相关标注已同步更新`)
		}
	}
	
	// 更新指定类别的所有标注颜色
	const updateAnnotationColors = async (categoryKey) => {
		if (!currentImage.value || !currentImage.value.annotations) return
		
		// 更新当前图片标注数据中的颜色引用
		let updatedCount = 0
		currentImage.value.annotations.forEach(annotation => {
			if (annotation.categoryId === categoryKey) {
				// 注意：标注数据本身不存储颜色，颜色来自类别定义
				updatedCount++
			}
		})
		
		console.log(`[Images] 已更新 ${updatedCount} 个标注的颜色引用`)
	}
	
	// 刷新标注显示
	const refreshAnnotationDisplay = () => {
		if (!currentImage.value || !annotationDrawer) {
			console.warn('[Images] 无法刷新标注显示：缺少图片或标注绘制器')
			return
		}
		
		
		console.log('[Images] 开始刷新标注显示...')
		
		// 强制清除标注覆盖层中的所有元素
		const overlayElement = imageContainerRef.value?.querySelector('.annotation-overlay')
		if (overlayElement) {
			overlayElement.innerHTML = ''
			console.log('[Images] 已清空标注覆盖层')
		}
		
		// 清除标注绘制器中的数据
		annotationDrawer.clearAllAnnotations()
		
		// 立即重新渲染所有标注（使用新的类别颜色）
		if (annotationsWithDetails.value && Array.isArray(annotationsWithDetails.value)) {
			console.log(`[Images] 重新渲染 ${annotationsWithDetails.value.length} 个标注`)
			
			// 使用nextTick确保DOM更新后再渲染
			nextTick(() => {
				annotationDrawer.renderExistingAnnotations(annotationsWithDetails.value)
				updateAnnotationHighlight() // 重新应用高亮
				console.log('[Images] 标注显示刷新完成')
				console.log('[Images] 刷新后的 imageTags:', imageTags.value.map(tag => ({
					key: tag.key,
					displayText: tag.displayText
				})))
			})
		} else {
			console.log('[Images] 没有标注需要渲染')
		}
	}

	// 更新标注高亮状态
	const updateAnnotationHighlight = () => {
		if (!imageContainerRef.value) return
		
		// 移除所有现有高亮
		const highlightedElements = imageContainerRef.value.querySelectorAll('.annotation-shape.highlighted')
		highlightedElements.forEach(el => el.classList.remove('highlighted'))
		
		// 如果有选中的标注，则为对应的 shape 元素添加高亮
		if (currentTag.value) {
			console.log('[Images] 尝试高亮标注:', currentTag.value)
			const targetContainer = imageContainerRef.value.querySelector(`#annotation-${currentTag.value}`)
			console.log('[Images] 找到的容器元素:', targetContainer)
			
			if (targetContainer) {
				// 尝试在容器内部寻找 shape 元素
				let shapeElement = targetContainer.querySelector('.annotation-shape')
				// 如果内部没有，则检查容器本身是否就是 shape 元素
				if (!shapeElement && targetContainer.classList.contains('annotation-shape')) {
					shapeElement = targetContainer
				}
				
				if (shapeElement) {
					shapeElement.classList.add('highlighted')
					console.log('[Images] 标注高亮成功:', currentTag.value)
				} else {
					console.warn('[Images] 未找到shape元素:', currentTag.value)
				}
			} else {
				console.warn('[Images] 未找到标注容器:', `#annotation-${currentTag.value}`)
			}
		}
	}

	// 开始编辑类别
	const handleEditCategoryStart = (category) => {
		editingCategory.value = category.key
		editingCategoryTitle.value = category.title
		// 下一个tick后聚焦输入框
		setTimeout(() => {
			const input = document.querySelector('.category-input')
			if (input) {
				input.focus()
				input.select()
			}
		}, 0)
	}

	// 保存类别编辑
	const handleSaveCategory = async (categoryKey) => {
		if (editingCategoryTitle.value.trim()) {
			const category = imageTypes.value.find(type => type.key === categoryKey)
			if (category) {
				category.title = editingCategoryTitle.value.trim()
				
				// 保存到当前图片
				await saveCategoriesToCurrentImage()
				
				ElMessage.success('编辑类别成功')
			}
		}
		cancelEditCategory()
	}

	// 取消编辑类别
	const cancelEditCategory = () => {
		editingCategory.value = null
		editingCategoryTitle.value = ''
	}

	// 删除类别
	const handleDeleteCategory = (categoryKey) => {
		if (imageTypes.value.length <= 1) {
			ElMessage.warning('至少需要保留一个类别')
			return
		}
		
		ElMessageBox.confirm(
			'确定要删除这个类别吗？删除后该类别的所有标注也会被移除。',
			'删除类别',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(async () => {
			const index = imageTypes.value.findIndex(type => type.key === categoryKey)
			if (index > -1) {
				// 删除类别
				imageTypes.value.splice(index, 1)
				
				// 删除该类别的所有标注
				if (currentImage.value?.annotations) {
					currentImage.value.annotations = currentImage.value.annotations.filter(
						annotation => annotation.categoryId !== categoryKey
					)
				}
				
				// 如果删除的是当前选中的类别，选择第一个类别
				if (currentType.value === categoryKey && imageTypes.value.length > 0) {
					currentType.value = imageTypes.value[0].key
				} else if (imageTypes.value.length === 0) {
					currentType.value = null
				}
				
				// 保存到当前图片
				await saveCategoriesToCurrentImage()
				
				// 刷新显示以更新类别信息
				refreshAnnotationDisplay()
				
				ElMessage.success('删除类别成功')
			}
		}).catch(() => {
			// 用户取消删除
		})
	}

	const handleDeleteTag = (tagKey) => {
		ElMessageBox.confirm(
			'确定要删除这个标注吗？',
			'删除标注',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(async () => {
			// 这里需要从当前图像的标注数据中删除指定的标注
			if (currentImage.value && currentImage.value.annotations) {
				const index = currentImage.value.annotations.findIndex(annotation => annotation.id === tagKey)
				if (index > -1) {
					const annotationToDelete = currentImage.value.annotations[index]
					
					// 删除对应的缩略图文件
					if (annotationToDelete.thumbnailData && project.value?.path) {
						try {
							const fileName = `${currentImage.value.id}_${annotationToDelete.id}.jpg`
							if (window.electronAPI?.deleteThumbnail) {
								const result = await window.electronAPI.deleteThumbnail(project.value.path, fileName)
								if (result.success) {
									console.log('[Images] 缩略图文件删除成功:', fileName)
								} else {
									console.warn('[Images] 缩略图文件删除失败:', result.error)
								}
							}
						} catch (error) {
							console.error('[Images] 删除缩略图文件异常:', error)
						}
					}
					
					// 从标注数组中删除
					currentImage.value.annotations.splice(index, 1)
					
					// 保存图片数据到项目
					await saveImageDataToProject()
					
					// 刷新标注显示以移除已删除的标注
					refreshAnnotationDisplay()
					
					ElMessage.success('删除标注成功')
				}
			}
		}).catch(() => {
			// 用户取消删除
		})
	}

	// 移动标注图层
	const moveAnnotationLayer = async (direction) => {
		if (!currentTag.value) {
			ElMessage.warning('请先在列表中选择一个标注')
			return
		}
		
		const annotations = currentImage.value.annotations
		const currentAnnotation = annotations.find(ann => ann.id === currentTag.value)
		
		if (!currentAnnotation) return
		
		// 获取所有标注的zIndex，如果没有则初始化
		annotations.forEach((ann, index) => {
			if (typeof ann.zIndex !== 'number') {
				ann.zIndex = index
			}
		})
		
		// 按zIndex排序获取当前的层级顺序
		const sortedAnnotations = [...annotations].sort((a, b) => a.zIndex - b.zIndex)
		const currentZIndex = currentAnnotation.zIndex
		const currentLayerIndex = sortedAnnotations.findIndex(ann => ann.id === currentTag.value)
		
		let moved = false
		
		if (direction === 'up') {
			// 上移：与上一层交换zIndex
			if (currentLayerIndex < sortedAnnotations.length - 1) {
				const upperAnnotation = sortedAnnotations[currentLayerIndex + 1]
				const upperZIndex = upperAnnotation.zIndex
				
				// 交换zIndex
				currentAnnotation.zIndex = upperZIndex
				upperAnnotation.zIndex = currentZIndex
				
				moved = true
				console.log(`[Images] 上移标注 ${currentTag.value}: ${currentZIndex} -> ${upperZIndex}`)
			} else {
				ElMessage.info('已经是顶层')
				return
			}
		} else if (direction === 'down') {
			// 下移：与下一层交换zIndex
			if (currentLayerIndex > 0) {
				const lowerAnnotation = sortedAnnotations[currentLayerIndex - 1]
				const lowerZIndex = lowerAnnotation.zIndex
				
				// 交换zIndex
				currentAnnotation.zIndex = lowerZIndex
				lowerAnnotation.zIndex = currentZIndex
				
				moved = true
				console.log(`[Images] 下移标注 ${currentTag.value}: ${currentZIndex} -> ${lowerZIndex}`)
			} else {
				ElMessage.info('已经是底层')
				return
			}
		}
		
		if (moved) {
			// 保存更改
			await saveImageDataToProject()
			
			// 刷新显示
			refreshAnnotationDisplay()
			
			ElMessage.success('图层顺序已更新')
		}
	}
	
	// 保存图片数据（包括类别和标注）到项目
	const saveImageDataToProject = async () => {
		if (!currentImage.value || !project.value) return
		
		try {
			// 确保当前图片有初始化的数据结构
			if (!currentImage.value.categories) {
				currentImage.value.categories = []
			}
			if (!currentImage.value.annotations) {
				currentImage.value.annotations = []
			}
			
			// 更新项目中对应图像的数据
			const updatedProject = { ...project.value }
			if (updatedProject.images) {
				const imageIndex = updatedProject.images.findIndex(img => img.id === currentImage.value.id)
				if (imageIndex > -1) {
					updatedProject.images[imageIndex] = { ...currentImage.value }
				}
			}
			
			// 更新store中的项目数据
			projectStore.setProject(updatedProject)
			projectStore.setImageInfo(currentImage.value)
			
			// 保存到文件
			await projectStore.saveProject()
			console.log('[Images] 图片数据已保存')
		} catch (error) {
			console.error('[Images] 保存图片数据失败:', error)
			ElMessage.error('保存图片数据失败: ' + error.message)
		}
	}

	// 鼠标位置追踪
	const { mousePosition, setImageElement, resetPosition } = useMouseTracker()
	const imageRef = ref(null)
	const imageContainerRef = ref(null)
	
	// 标注绘制工具
	const annotationDrawer = useAnnotationDrawer()
	
	// 图像加载完成处理
	const handleImageLoad = () => {
		console.log('[Images] 图像加载完成')
		if (imageRef.value) {
			setImageElement(imageRef.value)
			
			// 初始化标注绘制器
			if (imageContainerRef.value) {
				console.log('[Images] 初始化标注绘制器')
				annotationDrawer.initialize(imageContainerRef.value, imageRef.value)
				
				// 设置标注完成回调
				annotationDrawer.setOnAnnotationComplete(handleAnnotationComplete)
				
				// 同步线条宽度和当前设置
				annotationDrawer.setLineWidth(lineWidth.value)
				annotationDrawer.setAnnotationMode(annotationMode.value)
				
				// 如果有选中的类别，同步到标注绘制器
				if (currentType.value && imageTypes.value.length > 0) {
					const currentCategory = imageTypes.value.find(type => type.key === currentType.value)
					if (currentCategory) {
						console.log('[Images] 设置当前类别:', currentCategory)
						annotationDrawer.setCurrentCategory(currentCategory)
					}
				}
			}
		}
	}
	
	// 标注完成回调
	const handleAnnotationComplete = async (annotation) => {
		console.log('[Images] 标注完成回调被调用:', annotation)

		if (!currentImage.value) return
		
		// 检查是否有类别和有效的categoryId
		if (!imageTypes.value || imageTypes.value.length === 0) {
			ElMessage.error('没有可用的类别，无法创建标注')
			return
		}
		
		if (!annotation.categoryId) {
			ElMessage.error('标注缺少类别信息，创建失败')
			return
		}
		
		// 验证categoryId是否有效
		const category = imageTypes.value.find(type => type.key === annotation.categoryId)
		if (!category) {
			ElMessage.error('标注的类别不存在，创建失败')
			return
		}
		
		// 确保图片有标注数组
		if (!currentImage.value.annotations) {
			currentImage.value.annotations = []
		}
		
		// 计算新标注的zIndex（应该在最顶层）
		const maxZIndex = currentImage.value.annotations.length > 0 
			? Math.max(...currentImage.value.annotations.map(ann => 
				typeof ann.zIndex === 'number' ? ann.zIndex : 0
			)) 
			: -1
		const newZIndex = maxZIndex + 1
		
		console.log('[Images] 创建新标注:', {
			id: annotation.id,
			type: annotation.type,
			categoryId: annotation.categoryId,
			zIndex: newZIndex,
			maxZIndex: maxZIndex
		})
		
		// 获取标注的类别颜色信息
		const currentCategory = imageTypes.value.find(type => type.key === annotation.categoryId)
		const annotationColor = currentCategory?.color || '#409EFF'
		
		// 将颜色信息添加到标注对象中
		const annotationWithColor = {
			...annotation,
			color: annotationColor
		}
		
		// 生成标注区域的缩略图
		let thumbnailData = null
		try {
			if (currentImage.value.path) {
				console.log('[Images] 当前图片信息:', currentImage.value)
				console.log('[Images] 项目信息:', project.value)
				console.log('[Images] 标注颜色信息:', annotationColor)
				
				// 构建完整的图片路径
				let fullImagePath = currentImage.value.path
				if (!fullImagePath.startsWith('/') && project.value?.path) {
					fullImagePath = `${project.value.path}/${currentImage.value.path}`
				}
				
				console.log('[Images] 使用图片路径:', fullImagePath)
				thumbnailData = await cropAnnotationImage(fullImagePath, annotationWithColor, project.value.path, currentImage.value.id, 150)
				console.log('[Images] 标注缩略图生成成功:', annotation.id)
			}
		} catch (error) {
			console.error('[Images] 标注缩略图生成失败:', error)
		}

		// 添加标注到当前图片
		const newAnnotation = {
			id: annotation.id,
			type: annotation.type,
			categoryId: annotation.categoryId,
			x: annotation.x || 0,
			y: annotation.y || 0,
			width: annotation.width || 0,
			height: annotation.height || 0,
			points: annotation.points || null,
			zIndex: newZIndex,
			thumbnailData: thumbnailData // 保存缩略图数据
		}
		
		currentImage.value.annotations.push(newAnnotation)
		console.log('[Images] 新标注已添加到数组，当前标注总数:', currentImage.value.annotations.length)
		
		// 记录新创建的标注ID
		newAnnotationIds.value.push(annotation.id)
		console.log('[Images] 新标注已记录:', annotation.id, '新标注总数:', newAnnotationIds.value.length)
		
		// 保存到项目
		await saveImageDataToProject()
		
		// 刷新显示以更新所有标签的序号
		refreshAnnotationDisplay()
		
		console.log('[Images] 标注已添加到图片数据:', {
			id: annotation.id,
			type: annotation.type,
			categoryId: annotation.categoryId,
			zIndex: newZIndex
		})
		console.log('[Images] 当前所有标注:', currentImage.value.annotations.map(ann => ({
			id: ann.id,
			zIndex: ann.zIndex,
			categoryId: ann.categoryId
		})))
		ElMessage.success(`标注已添加: ${annotation.title}`)
	}

	// 图像缓存
	const imageDataCache = ref(new Map())

	// 获取图像 URL
	const getImageUrl = (item) => {
		if (!item) {
			return getPlaceholderImage()
		}
		
		// 如果已经是完整URL，直接返回
		if (item.image && (item.image.startsWith('http') || item.image.startsWith('data:'))) {
			return item.image
		}
		
		// 检查缓存
		if (imageDataCache.value.has(item.id)) {
			return imageDataCache.value.get(item.id)
		}
		
		// 构建本地文件路径并异步加载
		if (item.path && project.value?.path) {
			const fullImagePath = `${project.value.path}/${item.path}`
			
			// 异步加载图片数据
			loadImageData(item.id, fullImagePath)
			
			// 先返回占位图，加载完成后会自动更新
			return getPlaceholderImage()
		}
		
		// 如果没有路径信息，使用占位图
		console.warn('[Images] 图像路径信息不完整:', item)
		return getPlaceholderImage()
	}

	// 异步加载图像数据
	const loadImageData = async (imageId, imagePath) => {
		try {
			if (window.electronAPI?.getLocalImageData) {
				const result = await window.electronAPI.getLocalImageData(imagePath)
				if (result.success) {
					// 使用reactive方式更新缓存，确保Vue能检测到变化
					imageDataCache.value = new Map(imageDataCache.value.set(imageId, result.data))
				} else {
					console.error('[Images] 加载图片失败:', result.error)
				}
			}
		} catch (error) {
			console.error('[Images] 加载图片数据异常:', error)
		}
	}

	// 获取占位图像
	const getPlaceholderImage = () => {
		return ''
	}

	// 图像加载错误处理
	const handleImageError = (event) => {
		console.warn('[Images] 图像加载失败:', event.target.src)
		// 设置默认占位图
		event.target.src = getPlaceholderImage()
	}
	// 跳转处理标记，避免重复处理
	const isProcessingRouteJump = ref(false)
	
	// 处理路由参数，支持从 Inspect 页面跳转过来
	const handleRouteParams = () => {
		console.log('[Images] 处理路由参数:', route.query)
		
		const { imageId, annotationId } = route.query
		
		if (imageId && annotationId && !isProcessingRouteJump.value) {
			isProcessingRouteJump.value = true
			console.log(`[Images] 需要跳转到图片 ${imageId} 并选中标注 ${annotationId}`)
			
			// 查找对应的图片
			const targetImage = project.value?.images?.find(img => img.id === imageId)
			if (targetImage) {
				console.log('[Images] 找到目标图片:', targetImage.name)
				
				// 切换到目标图片
				projectStore.setImageInfo(targetImage)
				projectStore.setCurrentImg(targetImage.id)
				
				// 等待图片切换完成后选中标注
				setTimeout(() => {
					selectAnnotationById(annotationId)
					isProcessingRouteJump.value = false
				}, 800) // 增加延时确保图片和标注都加载完成
			} else {
				console.warn('[Images] 未找到目标图片:', imageId)
				ElMessage.warning('未找到指定的图片')
				isProcessingRouteJump.value = false
			}
			
			// 清除路由参数，避免重复处理
			router.replace({ name: 'Images' })
		}
	}
	
	// 根据ID选中标注
	const selectAnnotationById = (annotationId) => {
		console.log('[Images] 尝试选中标注:', annotationId, '类型:', typeof annotationId)
		
		if (!currentImage.value?.annotations) {
			console.warn('[Images] 当前图片没有标注数据')
			return
		}
		
		// 查找对应的标注
		const targetAnnotation = currentImage.value.annotations.find(ann => ann.id === annotationId)
		if (targetAnnotation) {
			console.log('[Images] 找到目标标注:', targetAnnotation)
			
			// 选中该标注（使用标注的ID作为key）
			currentTag.value = targetAnnotation.id
			currentType.value = null // 清空类别选中
			
			// 等待DOM更新后再高亮显示，确保列表已渲染
			nextTick(() => {
				updateAnnotationHighlight()
				
				// 验证选中状态
				console.log('[Images] 当前选中标注ID:', currentTag.value, '类型:', typeof currentTag.value)
				console.log('[Images] 当前imageTags列表:', imageTags.value.map(tag => ({
					key: tag.key,
					keyType: typeof tag.key,
					displayText: tag.displayText,
					isSelected: tag.key == currentTag.value
				})))
				
				ElMessage.success('已跳转到指定标注')
			})
			
			console.log('[Images] 标注选中成功:', targetAnnotation.id)
		} else {
			console.warn('[Images] 未找到目标标注:', annotationId)
			ElMessage.warning('未找到指定的标注')
		}
	}

	// 初始化数据
	onMounted(async () => {
		console.log('[Images] 标注页面初始化')
		console.log('[Images] 当前项目:', project.value)
		console.log('[Images] 当前图像:', currentImage.value)
		
		// 加载本地方法配置
		try {
			if (window.electronAPI?.getLocalMethods) {
				const result = await window.electronAPI.getLocalMethods()
				if (result.success && result.config) {
					instanceList.value = result.config.methods || []
					console.log('[Images] 加载方法配置成功:', instanceList.value)
				}
			}
		} catch (error) {
			console.error('[Images] 加载方法配置失败:', error)
		}
		
		// 如果没有选中图像且项目中有图像，选中第一张
		if (!currentImage.value && project.value?.images && project.value.images.length > 0) {
			const firstImage = project.value.images[0]
			projectStore.setImageInfo(firstImage)
			projectStore.setCurrentImg(firstImage.id)
			console.log('[Images] 自动选中第一张图像:', firstImage.name)
		}
		
		// 加载当前图片的类别数据
		loadCategoriesFromCurrentImage()
		
		// 延迟初始化标注绘制器，并自动加载标注
		setTimeout(() => {
			if (imageContainerRef.value && imageRef.value && currentImage.value) {
				annotationDrawer.initialize(imageContainerRef.value, imageRef.value)
				annotationDrawer.setOnAnnotationComplete(handleAnnotationComplete)
				annotationDrawer.setLineWidth(lineWidth.value)
				annotationDrawer.setAnnotationMode(annotationMode.value)
				
				// 如果有选中的类别，同步到标注绘制器
				if (currentType.value && imageTypes.value.length > 0) {
					const currentCategory = imageTypes.value.find(type => type.key === currentType.value)
					if (currentCategory) {
						annotationDrawer.setCurrentCategory(currentCategory)
					}
				}
				
				// 自动初始化标注显示
				// 渲染现有标注
				if (annotationsWithDetails.value && Array.isArray(annotationsWithDetails.value)) {
					console.log(`[Images] 渲染 ${annotationsWithDetails.value.length} 个标注`)
					annotationDrawer.renderExistingAnnotations(annotationsWithDetails.value)
					// 清空新标注ID列表
					newAnnotationIds.value = []
				}
				
				console.log('[Images] 标注绘制器已初始化并自动渲染标注')
			}
		}, 200)
		
		// 处理从 Inspect 页面跳转过来的路由参数
		// 只有在有路由参数时才延迟处理，避免不必要的延迟
		if (route.query.imageId && route.query.annotationId) {
			setTimeout(() => {
				handleRouteParams()
			}, 300) // 减少延迟时间
		}
	})
	
	// 监听当前图片变化，重新加载类别数据
	watch(currentImage, (newImage, oldImage) => {
		// 如果新旧 image 的 id 相同，说明是更新而非切换，跳过重置逻辑
		if (newImage && oldImage && newImage.id === oldImage.id) {
			console.log('[Images] 当前图片数据更新，跳过重置');
			return;
		}

		// 如果正在处理路由跳转，延迟执行避免重复处理
		if (isProcessingRouteJump.value) {
			console.log('[Images] 正在处理路由跳转，延迟图片切换处理')
			setTimeout(() => {
				if (!isProcessingRouteJump.value) {
					console.log('[Images] 当前图片变化，重新加载类别数据')
					loadCategoriesFromCurrentImage()
				}
			}, 100)
			return
		}

		console.log('[Images] 当前图片变化，重新加载类别数据')
		loadCategoriesFromCurrentImage()
		
		// 重置鼠标位置
		resetPosition()
		
		// 清空标注绘制器状态
		annotationDrawer.clearAllAnnotations()
		
		// 重置标注状态
		newAnnotationIds.value = []
		currentScale.value = 1.0 // 重置缩放比例
		
		// 如果图片变化，重新设置图像元素
		if (newImage !== oldImage) {
			setTimeout(() => {
				if (imageRef.value) {
					setImageElement(imageRef.value)
					// 重新初始化标注绘制器
					if (imageContainerRef.value) {
						annotationDrawer.initialize(imageContainerRef.value, imageRef.value)
						annotationDrawer.setOnAnnotationComplete(handleAnnotationComplete)
						annotationDrawer.setLineWidth(lineWidth.value)
						annotationDrawer.setAnnotationMode(annotationMode.value)
						
						// 如果有选中的类别，同步到标注绘制器
						if (currentType.value && imageTypes.value.length > 0) {
							const currentCategory = imageTypes.value.find(type => type.key === currentType.value)
							if (currentCategory) {
								annotationDrawer.setCurrentCategory(currentCategory)
							}
						}
						
						// 重新渲染现有标注
						if (annotationsWithDetails.value && Array.isArray(annotationsWithDetails.value)) {
							console.log(`[Images] 重新渲染 ${annotationsWithDetails.value.length} 个标注`)
							annotationDrawer.renderExistingAnnotations(annotationsWithDetails.value)
						}
						
						console.log('[Images] 图片已切换，标注绘制器已重新初始化并渲染标注')
					}
				} else {
					setImageElement(null)
				}
			}, 100) // 等待DOM更新
		}
	}, { deep: true })
	
	// 监听线条宽度变化
	watch(lineWidth, (newWidth) => {
		annotationDrawer.setLineWidth(newWidth)
	})
	
	// 监听当前类别变化
	watch(currentType, () => {
		if (currentType.value && imageTypes.value.length > 0) {
			const currentCategory = imageTypes.value.find(type => type.key === currentType.value)
			if (currentCategory) {
				annotationDrawer.setCurrentCategory(currentCategory)
			}
		}
	})
	
	// 监听类别数组变化，自动设置标注模式
	watch(imageTypes, (newTypes) => {
		if (newTypes && newTypes.length > 0) {
			// 有类别时，如果没有选中模式，默认选择"选择"模式
			if (!annotationMode.value) {
				annotationMode.value = 'select'
				annotationDrawer.setAnnotationMode('select')
			}
		} else {
			// 没有类别时，清空标注模式
			annotationMode.value = ''
			annotationDrawer.setAnnotationMode('')
		}
	}, { immediate: true })
</script>

<style scoped lang="scss">
.container {
	.sidebar {
		display: flex;
		flex-direction: column;
		padding: 0 0 23px 15px;
		background: transparent;
		border: 0;
		border-radius: 0;
		.sidebar-main{
			display: flex;
			flex-direction: column;
			gap: 10px;
			.custom-card{
				background: linear-gradient( 180deg, rgba(255,255,255,0.6) 0%, rgba(255,255,255,0.4) 100%);
				border-radius: 6px;
				border: 2px solid #FFFFFF;
				padding: 0;
				.card-header{
					width: 100%;
					cursor: pointer;
					padding: 10px 14px;
					display: flex;
					align-items: center;
					justify-content: space-between;
					
					.title{
						font-size: 14px;
						color: #333;
						display: flex;
						align-items: center;
						gap: 8px;
						font-weight: 500;
						cursor: pointer;
					}
				}
				.card-body{
					padding: 0 14px 14px;
					.card-text{
						font-size: 12px;
						color: #606266;
					}
				}
			}
			.custom-input{
				height: 50px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 15px;
				span{
					font-size: 14px;
					color: #222;
					font-weight: 600;
				}
			}
			
			.custom-info {
				display: flex;
				align-items: center;
				gap: 10px;
				height: 80px;
				padding: 0 15px;
				
				.info-circle{
					width: 35px;
					height: 35px;
					border-radius: 50%;
					background: #409EFF;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 18px;
					color: white;
					text-shadow: 0 1px 2px rgba(0,0,0,0.2);
					flex-shrink: 0;
				}
				
				.info-cont {
					flex: 1;
					
					.title {
						font-size: 14px;
						color: #333;
						margin-bottom: 4px;
						font-weight: 500;
					}
					
					.text {
						font-size: 12px;
						color: #666;
						line-height: 1.4;
					}
				}
			}
			
			.annotation-settings {
				.card-body {
					display: flex;
					flex-direction: column;
					gap: 15px;
					
					.setting-section {
						display: flex;
						flex-direction: column;
						gap: 8px;
						
						.setting-label {
							font-size: 12px;
							color: #606266;
							font-weight: 500;
						}
						
						.annotation-modes {
							display: flex;
							flex-wrap: wrap;
							gap: 8px;
							
							.mode-btn {
								display: flex;
								flex-direction: column;
								align-items: center;
								gap: 4px;
								padding: 8px 12px;
								border: 2px solid #E4E7ED;
								border-radius: 8px;
								cursor: pointer;
								transition: all 0.2s ease;
								background: white;
								min-width: 60px;
								
								&:hover {
									border-color: #409EFF;
									background: #F5F7FA;
								}
								
								&.active {
									border-color: #409EFF;
									background: #ECF5FF;
									color: #409EFF;
								}
								
								&.disabled {
									opacity: 0.5;
									cursor: not-allowed;
									background: #f5f5f5;
									border-color: #dcdfe6;
									color: #c0c4cc;
									
									&:hover {
										border-color: #dcdfe6;
										background: #f5f5f5;
									}
								}
								
								.el-icon {
									font-size: 16px;
								}
								
								span {
									font-size: 10px;
									font-weight: 500;
								}
							}
						}
						
						.line-width-control {
							display: flex;
							align-items: center;
							gap: 10px;
							
							.width-value {
								font-size: 12px;
								color: #606266;
								min-width: 30px;
								text-align: center;
							}
							
							.line-preview {
								width: 25px;
								border-radius: 2px;
								background: #000;
								transition: all 0.2s ease;
								flex-shrink: 0;
							}
						}
					}
				}
			}
			
			.custom-types{
				.card-body{
					display: flex;
					flex-direction: column;
					gap: 10px;
					.cell-box{
						background: linear-gradient( 180deg, rgba(255,255,255,0.6) 0%, rgba(255,255,255,0.4) 100%);
						border-radius: 6px;
						border: 1px solid #DCE1E6;
						overflow-y: auto;
						height: 182px;
						.citem{
							padding: 0 7px;
							position: relative;
							
							&:hover {
								.category-actions {
									opacity: 1;
								}
							}
							
							.color-picker-wrapper {
								width: 16px;
								height: 16px;
								border-radius: 4px;
								border: 1px solid #ddd;
								cursor: pointer;
								flex-shrink: 0;
								box-shadow: 0 1px 3px rgba(0,0,0,0.12);
								transition: all 0.2s ease;
								
								&:hover {
									transform: scale(1.1);
									box-shadow: 0 2px 8px rgba(0,0,0,0.15);
								}
							}
							
							.category-content {
								flex: 1;
								margin-left: 10px;
								font-weight: 500;
								color: #303133;
								
								/* 同时设置 span 和 input 的字体大小 */
								span, .category-input {
									font-size: 12px;
								}
								
								.category-input {
									border: 1px solid #DCDFE6;
									border-radius: 6px;
									padding: 4px 8px;
									width: 100%;
									background: white;
									font-weight: 500;
									transition: all 0.2s ease;
									
									&:focus {
										outline: none;
										border-color: #409EFF;
										box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
									}
								}
							}
							
							.category-actions {
								opacity: 0;
								transition: all 0.2s ease;
								display: flex;
								gap: 4px;
								margin-left: 8px;
								
								.action-icon {
									font-size: 16px;
									cursor: pointer;
									padding: 2px;
									border-radius: 4px;
									transition: all 0.2s ease;
									
									&.edit-icon {
										color: #909399;
										
										&:hover {
											background: #F2F6FC;
											color: #409EFF;
											transform: scale(1.1);
										}
									}
									
									&.delete-icon {
										color: #909399;
										
										&:hover {
											background: #FEF0F0;
											color: #F56C6C;
											transform: scale(1.1);
										}
									}
								}
							}
							
							div{
								font-size: 12px;
							}
						}
						.cell{
							gap: 8px;
							min-height: 45px;
							padding: 8px 12px;
							display: flex;
							align-items: center;
							justify-content: flex-start;
							cursor: pointer;
							border-radius: 6px;
							transition: background-color 0.2s ease;
							
							&:hover {
								background-color: #f5f7fa;
							}
							
							div{
								font-size: 10px;
								color: #303133;
							}
							.end{
								margin-left: auto;
							}
						}
						.active{
							background: rgba(245,34,45,0.07);
						}
						
						.tag-item {
							&:hover {
								.tag-actions {
									opacity: 1;
								}
							}
							
							.color {
								width: 16px;
								height: 16px;
								border-radius: 4px;
								border: 1px solid #e0e0e0;
								flex-shrink: 0;
							}
							
							.tag-info {
								flex: 1;
								display: flex;
								flex-direction: column;
								gap: 4px;
								margin-left: 12px;
								
								.tag-title {
									font-size: 12px;
									color: #303133;
									font-weight: 500;
									line-height: 1.2;
								}
								
								.tag-coords {
									font-size: 11px;
									color: #909399;
									line-height: 1.2;
								}
								
								.tag-area {
									font-size: 11px;
									color: #67C23A;
									line-height: 1.2;
									font-weight: 500;
								}
							}
							
							.tag-actions {
								opacity: 0;
								transition: opacity 0.2s;
								display: flex;
								gap: 4px;
								margin-left: 8px;
								
								.action-icon {
									font-size: 16px;
									cursor: pointer;
									padding: 2px;
									border-radius: 4px;
									transition: background-color 0.2s;
									
									&.edit-icon {
										color: #909399;
										
										&:hover {
											background: #F2F6FC;
											color: #409EFF;
										}
									}
									
									&.delete-icon {
										color: #909399;
										
										&:hover {
											background: #FEF0F0;
											color: #F56C6C;
										}
									}
								}
							}
						}
					}
					.card-buttons{
						display: flex;
						justify-content: flex-end;
						align-items: center;
						.btn{
							width: 90px;
							height: 30px;
							border-radius: 16px;
							border: 1.5px solid #2165F8;
							color: #2165F8;
							font-size: 12px;
							font-weight: 500;
							display: flex;
							align-items: center;
							justify-content: center;
							cursor: pointer;
							user-select: none;
						}
						.btn-left{
							margin-right: auto;
						}
					}
				}
			}
		}
	}
	.content{
		position: relative;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		.tags-box{
			display: flex;
			flex-wrap: wrap;
			gap: 10px;
			position: absolute;
			left: 20px;
			top: 20px;
			z-index: 10;
			.tag{
				width: 80px;
				height: 30px;
				border: 1.5px solid #2165F8;
				cursor: pointer;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 5px;
				border-radius: 60px;
				user-select: none;
				color: #2165F8;
				background: rgba(255, 255, 255, 0.9);
				transition: all 0.2s ease;
				
				&:hover {
					background: rgba(33, 101, 248, 0.1);
					transform: translateY(-1px);
				}
				
				&.active {
					background: #2165F8;
					color: white;
					
					span {
						color: white;
					}
				}
				
				&.loaded {
					background: #67C23A;
					color: white;
					border-color: #67C23A;
					
					span {
						color: white;
					}
				}
				
				&.disabled {
					background: #F5F7FA;
					color: #C0C4CC;
					border-color: #E4E7ED;
					cursor: not-allowed;
					
					&:hover {
						background: #F5F7FA;
						transform: none;
					}
					
					span {
						color: #C0C4CC;
					}
				}
				
				&.divider {
					width: 2px;
					height: 20px;
					background: #E4E7ED;
					border: none;
					border-radius: 1px;
					cursor: default;
					
					&:hover {
						transform: none;
						background: #E4E7ED;
					}
				}
				
				span{
					color: #2165F8;
					font-size: 12px;
					font-weight: 500;
				}
			}
		}
		.content-main{
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.image-container {
				position: relative;
				max-width: 90%;
				max-height: 90%;
				
				.img{
					max-width: 100%;
					max-height: 100%;
					object-fit: contain;
					border-radius: 8px;
					box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
				}
				
				.annotation-overlay {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					pointer-events: none;
					
					:deep(.annotation-shape.highlighted) {
						/* For SVG elements */
						stroke: #FF5722 !important;
						stroke-width: 3px !important;
						stroke-dasharray: 8, 4;
						
						/* For DIV elements (using border to simulate stroke) */
						border-style: dashed !important;
						border-color: #FF5722 !important;
						border-width: 3px !important;
					}
				}
			}
			
			&.no-image {
				.no-image-placeholder {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					gap: 16px;
					color: #909399;
					
					p {
						margin: 0;
						font-size: 14px;
					}
				}
			}
		}
		.custom-footer{
			position: absolute;
			bottom: 30px;
			left: 20px;
			display: grid;
			grid-template-columns: 1fr auto auto;
			background: rgba(255, 255, 255, 0.95);
			backdrop-filter: blur(8px);
			box-shadow: 0px 0px 12px 0px rgba(0,0,0,0.06);
			border-radius: 10px;
			border: 2px solid #FFFFFF;
			width: calc(100% - 40px);
			div{
				height: 42px;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 12px;
				color: #303133;
				font-weight: 800;
				padding: 0 12px;
				
				&:first-child {
					justify-content: flex-start;
					flex: 1;
					min-width: 0;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
				
				&.rgb-info {
					display: flex;
					align-items: center;
					gap: 8px;
					
					span {
						font-size: 12px;
					}
					
					.color-preview {
						width: 20px;
						height: 20px;
						border-radius: 4px;
						border: 1px solid #ddd;
						flex-shrink: 0;
						cursor: pointer;
						transition: transform 0.2s ease;
						
						// 鼠标放入
						&:hover {
							transform: scale(1.1);
						}
					}
				}
			}
		}
	}
}

/* 颜色选择器对话框样式 */
.color-picker-dialog {
	padding: 20px 0;
	
	.color-picker-section {
		display: flex;
		align-items: center;
		gap: 15px;
		margin-bottom: 25px;
		
		label {
			font-size: 14px;
			color: #303133;
			font-weight: 500;
			min-width: 80px;
		}
		
		.native-color-picker {
			width: 60px;
			height: 40px;
			border: 2px solid #DCDFE6;
			border-radius: 6px;
			cursor: pointer;
			background: none;
			
			&::-webkit-color-swatch-wrapper {
				padding: 0;
				border: none;
				border-radius: 4px;
			}
			
			&::-webkit-color-swatch {
				border: none;
				border-radius: 4px;
			}
		}
		
		.color-value {
			font-family: 'Courier New', monospace;
			font-size: 14px;
			color: #606266;
			background: #F5F7FA;
			padding: 8px 12px;
			border-radius: 4px;
			border: 1px solid #DCDFE6;
			min-width: 80px;
			text-align: center;
		}
	}
	
	.preset-colors-section {
		.preset-title {
			font-size: 14px;
			color: #303133;
			font-weight: 500;
			margin-bottom: 12px;
		}
		
		.preset-colors-grid {
			display: grid;
			grid-template-columns: repeat(6, 1fr);
			gap: 10px;
			
			.preset-color-item {
				width: 40px;
				height: 30px;
				border-radius: 6px;
				border: 2px solid #E4E7ED;
				cursor: pointer;
				transition: all 0.2s ease;
				
				&:hover {
					transform: scale(1.05);
					box-shadow: 0 2px 8px rgba(0,0,0,0.15);
					border-color: #409EFF;
				}
			}
		}
	}
}

/* 无数据提示样式 */
.no-data-hint {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 40px 20px;
	color: #909399;
	text-align: center;
	
	.el-icon {
		margin-bottom: 12px;
		opacity: 0.6;
	}
	
	p {
		margin: 0;
		font-size: 12px;
		line-height: 1.4;
	}
}

</style>